package net.kevin.demo.hessian.module;

import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.caucho.hessian.client.HessianProxyFactory;

public class InterfaceDependOnRegistry implements ApplicationContextAware, BeanFactoryPostProcessor {
	private ApplicationContext act;
	private Set<Module> modules;

	public Set<Module> getModules() {
		return modules;
	}

	public void setModules(Set<Module> modules) {
		this.modules = modules;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		act = applicationContext;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		for (Module module : modules) {
			HessianProxyFactory factory = new HessianProxyFactory();
			String url = module.getEndpoint();
			for (String facade : module.getFacades()) {
				String name = facade.substring(facade.lastIndexOf(".") + 1) + "Remote";
				name = name.substring(0, 1).toLowerCase() + name.substring(1);
				try {
					Class<?> clazz = act.getClassLoader().loadClass(facade);
					beanFactory.registerSingleton(name, factory.create(clazz, url));
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
}
